package com.yang.tools.httpdownloader;

import java.util.List;

import com.yang.tools.util.HttpUtil;
import com.yang.tools.util.PathUtil;

public class HttpDownloader
{
	private HttpUtil httpUtil = new HttpUtil();

	public void download(String url, String destPath)
	{
		try
		{
			String content = httpUtil.getResponseSource(url);
			HtmlParser parser = new HtmlParser();
			parser.findLinks(url, content);
			downloadFiles(parser.getFileLinks(), destPath);
			downloadFolders(parser.getFolderLinks(), destPath);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}

	private void downloadFolders(List<String> folderLinks, String destPath)
	{
		destPath = PathUtil.completeTheTailSlash(destPath);
		for (int i = 0; i < folderLinks.size(); i++)
		{
			String folderulr = folderLinks.get(i);
			new HttpDownloader().download(folderulr,
					destPath + PathUtil.getLastFolderName(folderulr));
		}
	}

	private void downloadFiles(List<String> filelinks, String destFolder)
			throws Exception
	{
		for (int i = 0; i < filelinks.size(); i++)
		{
			httpUtil.download(filelinks.get(i), destFolder);
		}
	}
}
